package com.netease.financial.base.lockpattern;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.text.TextUtils;

import com.netease.financial.base.lockpattern.patternunlock.PatternUnlockActivity;
import com.netease.financial.base.web.WebStoragePreferencesHelper;
import com.netease.financial.common.util.NfsLog;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by hzwuyufeng on 1/15/16.
 */
public class LockPatternHelper {

    private static final String TAG = LockPatternHelper.class.getSimpleName();

    private static final long LOCK_PATTERN_TIMEOUT = 5 * 60 * 1000;

    private static final Set<String> mWhiteLists = new HashSet<>();

    public static void init(Context context) {
        LockPatternModule.init(context);
    }

    public static void setUserId(String userId) {
        if (TextUtils.isEmpty(userId)) {
            unlockForUser(userId);
        }
        LockPatternPreferencesHelper.setUserId(userId);
    }

    public static String getClientId() {
        return LockPatternPreferencesHelper.getClientId();
    }

    public static void setClientId(String clientId) {
        LockPatternPreferencesHelper.setClientId(clientId);
    }

    public static void appWillEnterForeground(Activity activity) {
        handleLoginTimeOutEvent();
//        handleLockPatternEvent(activity);
    }

    public static void onActivityResumed(Activity activity) {
        handleLockPatternEvent(activity);
    }

    private static void handleLockPatternEvent(Activity activity) {
        String userId = getCurrentUserId();
        if (TextUtils.isEmpty(userId)) {
            NfsLog.d(TAG, "userId is empty");
            return;
        }

        if (isLockPatternExistsForUser(userId)) {
            showLockPatternIfNeed(activity);
        } else {
            showLockPatternCreateScreenIfNeed(activity, userId, 20000);
        }
    }

    public static void appDidEnterBackground(Activity activity) {
        LockPatternPreferencesHelper.setLastAppEnterBackgroundTime(System.currentTimeMillis());
//        if (activity instanceof PatternUnlockActivity) {
//            activity.finish();
//        }
    }

    public static String getCurrentUserId() {
        return LockPatternPreferencesHelper.getUserId();
    }

    public static boolean isLockPatternExistsForUser(String userId) {
        return havePattern(userId);
    }

    public static void setLockPatternForUser(List<LockPatternView.Cell> pattern, String userId) {
        LockPatternModule.getLockPatternUtils().saveLockPattern(pattern, userId);
        LockPatternPreferencesHelper.setLastAppEnterBackgroundTime(System.currentTimeMillis());
    }

    public static void clearLockPatternForUser(String userId) {
        LockPatternModule.getLockPatternUtils().clearLock(userId);
    }

    public static boolean checkPattern(List<LockPatternView.Cell> pattern, String userId) {
        return LockPatternModule.getLockPatternUtils().checkPattern(pattern, userId);
    }

    public static boolean havePattern(String userId) {
        return LockPatternModule.getLockPatternUtils().havePattern(userId);
    }

    public static void unlockForUser(String userId) {
        LockPatternPreferencesHelper.setFailedAttemptsSinceLastTimeout(0);
        LockPatternPreferencesHelper.setLoginTimeOut(false);
    }

    public static boolean shouldShowLockPattern(Activity activity, String userId) {
        if (TextUtils.isEmpty(userId)) {
            NfsLog.d(TAG, "userId is empty");
            return false;
        }
        if (!isLoginTimeOut()) {
            NfsLog.d(TAG, "not need pattern lock");
            return false;
        }
        if (isActivityInWhiteList(activity)) {
            NfsLog.d(TAG, "is in white list");
            NfsLog.d(TAG, "activity:" + activity.getClass().getSimpleName());
            return false;
        }

        return isLockPatternExistsForUser(userId);
    }

    public static boolean shouldShowLockPatternCreateScreen(Activity activity, String userId) {
        NfsLog.d(TAG, "enter.shouldShowLockPatternCreateScreen");
        if (TextUtils.isEmpty(userId)) {
            NfsLog.d(TAG, "userId is empty");
            return false;
        }

        if (isActivityInWhiteList(activity)) {
            NfsLog.d(TAG, "is in white list");
            NfsLog.d(TAG, "activity:" + activity.getClass().getSimpleName());
            return false;
        }

        return !isLockPatternExistsForUser(userId);
    }

    public static boolean isLoginTimeOut() {
        return LockPatternPreferencesHelper.isLoginTimeOut();
    }

    private static void showLockPattern(Activity activity, String userId) {
        String headPortraitUrl = WebStoragePreferencesHelper.getLocalStorageItem(WebStoragePreferencesHelper.KEY_LOCAL_STORAGE_HEAD_PORTRAIT_URL);
        Intent intent = PatternUnlockActivity.getCallingIntent(activity, getClientId(), headPortraitUrl, userId);
        activity.startActivity(intent);
    }

    public static void showLockPatternIfNeed(Activity activity, String userId) {
        if (shouldShowLockPattern(activity, userId)) {
            showLockPattern(activity, userId);
        }
    }

    public static void showLockPatternIfNeed(Activity activity) {
        showLockPatternIfNeed(activity, getCurrentUserId());
    }

    public static void showLockPatternCreateScreenIfNeed(Activity activity, String userId, int requestCode) {
        if (shouldShowLockPatternCreateScreen(activity, userId)) {
            showLockPatternCreateScreen(activity, userId, requestCode);
        }
    }

    public static void showLockPatternCreateScreen(Activity activity, String userId, int requestCode) {
        Intent intent = CreateLockPatternActivity.getCallingIntent(activity, userId);
        activity.startActivityForResult(intent, requestCode);
    }

    public static void showLockPatternCreateScreen(Fragment fragment, String userId, int requestCode) {
        Intent intent = CreateLockPatternActivity.getCallingIntent(fragment.getContext(), userId);
        fragment.startActivityForResult(intent, requestCode);
    }

    public static void showLockPatternCreateScreen(Activity activity, int requestCode) {
        showLockPatternCreateScreen(activity, LockPatternHelper.getCurrentUserId(), requestCode);
    }

    public static void registerIntoWhiteList(String activityName) {
        mWhiteLists.add(activityName);
    }

    private static boolean isActivityInWhiteList(Activity activity) {
        return mWhiteLists.contains(activity.getClass().getName());
    }

    private static void handleLoginTimeOutEvent() {
        long lastStopTime = LockPatternPreferencesHelper.getLastAppEnterBackgroundTime();
        long currentTime = System.currentTimeMillis();
        long interval = currentTime - lastStopTime;

        boolean isTimeOut = interval > LOCK_PATTERN_TIMEOUT;
        if (isTimeOut && !TextUtils.isEmpty(getCurrentUserId())) {
            LockPatternPreferencesHelper.setLoginTimeOut(true);
        }
    }

}
